package org.allofus;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import java.nio.charset.StandardCharsets;

public class Main
{
    public static String encryptPassword(String pwd, String key) {
        try {
            Security.addProvider(new com.sun.crypto.provider.SunJCE());
            Key secretKey = getDesSecretKey(key);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] data = pwd.getBytes(StandardCharsets.UTF_8);
            byte[] result = cipher.doFinal(data);
            return new sun.misc.BASE64Encoder().encode(result);
        } catch (Exception e) {
            return null;
        }
    }

    public static String decryptPassword(String pwd, String key) throws Exception {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        Key aKey = getDesSecretKey(key);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, aKey);

        byte[] data = new sun.misc.BASE64Decoder().decodeBuffer(pwd);
        byte[] result = cipher.doFinal(data);

        return new String(result, StandardCharsets.UTF_8);
    }

    public static SecretKey getDesSecretKey(String key) {
        byte[] result = new byte[8];
        byte[] keys;
        keys = key.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < 8; i++) {
            if (i < keys.length) {
                result[i] = keys[i];
            } else {
                result[i] = 0x01;
            }
        }
        return new SecretKeySpec(result, "DES");
    }

    public static void main(String[] args) throws Exception {
        String password = encryptPassword("crmeb.com", "demo");
        System.out.println("The password " + password);
    }
}